package com.longyi.admin.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
import com.longyi.admin.annotation.Logging;
import com.longyi.admin.common.GetPath;
import com.longyi.admin.entity.User;
import com.longyi.admin.service.FileService;
import com.longyi.admin.entity.File;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import com.longyi.admin.common.QueryPageParam;
import com.longyi.admin.common.Result;
import org.springframework.web.multipart.MultipartFile;

/**
* File 前端控制器
*
* @author 龙毅
* @since 2025-08-27
*/
@RestController
@RequestMapping("/file")
public class FileController {

    // 注入service
    @Autowired
    private FileService fileService;
    private final String ip = "http://localhost:8888";

    /**
     * 获取不含后缀的文件名
     *
     * @param fileName 完整文件名
     * @return 去除后缀的文件名
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(0, index);
        } else {
            fileName = "";
        }
        return fileName;
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName 完整文件名
     * @return 文件扩展名（不含点）
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1);
        } else {
            return ""; // 文件没有后缀名

        }
    }

    @GetMapping("/{flag}")
//    @Logging(record = "文件下载" , type = "下载")
    public void filePath(@PathVariable String flag, HttpServletResponse httpServletResponse) throws IOException {

        String filePath = GetPath.getProjectPath() + "/file/";
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String targetFileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
//        System.out.println("targetFileName:" + targetFileName);
        try {
            if (StrUtil.isNotEmpty(targetFileName)) {
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetFileName, "UTF-8"));
                httpServletResponse.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + targetFileName);
                os = httpServletResponse.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
                System.out.println();
            }
        } catch (IORuntimeException e) {
            System.out.println(e.getMessage());
        }
    }

    @PostMapping("/upload")
    @Logging(record = "文件上传" , type = "上传")
    public Result upload(@RequestParam("file") MultipartFile file ,@RequestParam String name) {
        if (file.isEmpty()) {
            return Result.fail("上传不能为空");
        }
        //去/保留最后一个/后面的
        String fileName =getFileName(name);

        String ext = getFileExtension(name);
        String filePath = GetPath.getProjectPath() + "/file/";
        if (!FileUtil.isDirectory(filePath)) {
            FileUtil.mkdir(filePath);
        }
        OutputStream os;
        List<String> fileNames = FileUtil.listFileNames(filePath);
        String finalFileName = fileName;
        System.out.println(finalFileName);
        String targetFileName = fileNames.stream().filter(names -> names.contains(finalFileName)).findAny().orElse("");
        System.out.println("targetFileName:" + targetFileName);
        if (targetFileName.length() > 0) {
            List<File> list = fileService.lambdaQuery().eq(File::getName, fileName).eq(File::getType, ext).eq(File::getSize, file.getSize()).list();
            System.out.println(list);
            if(list.size() > 0){
                return Result.suc(list.get(0));
            }else{
                fileName = String.valueOf(System.currentTimeMillis());
            }
        }
        String flag = fileName + "." + ext;
        try {
            FileUtil.writeBytes(file.getBytes(), filePath + flag);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        File file1 = new File();
        file1.setName(fileName);
        file1.setType(ext);
        file1.setSize(file.getSize());
        file1.setUrl(ip + "/file/" + flag);
        file1.setCreateTime(LocalDateTime.now());
        fileService.save(file1);
        return Result.suc(file1);
    }
    @PostMapping("/modStatus/{id}")
    public Result modStatus(@PathVariable("id") Long id) {
        File file = fileService.getById(id);
        if (file.getStatus() == 1)
            file.setStatus(0);
        else
            file.setStatus(1);
        return fileService.updateById(file) ? Result.suc("修改成功")
                : Result.fail("修改失败");
    }
    // 统计数量
    @GetMapping("/count")
    public Integer count() {
        return Math.toIntExact(fileService.count());
    }

    // 获取列表
    @GetMapping("/list")
    @Logging(record = "文件列表" , type = "查询")
    public List<File> list() {
        return fileService.list();
    }

    // 新增数据
    @PostMapping("/save")
    @Logging(record = "文件新增" , type = "新增")
    public Result save(@RequestBody File file) {
        return fileService.save(file)
                ? Result.suc("新增成功")
                : Result.fail("新增失败");
    }

    // 修改数据
    @PostMapping("/update")
    @Logging(record = "文件修改" , type = "修改")
    public Result update(@RequestBody File file) {
        return fileService.updateById(file)
                ? Result.suc("修改成功")
                : Result.fail("修改失败");
    }

    // 获取详情
    @GetMapping("/info/{id}")
    @Logging(record = "文件详情" , type = "查询")
    public Result info(@PathVariable("id") Long id) {
        File file = fileService.getById(id);
        return Result.suc(file);
    }

    // 批量删除数据
    @Transactional
    @PostMapping("/deleteBatch")
    @Logging(record = "文件批量删除" , type = "删除")
    public Result deleteBatch(@RequestBody Long[] ids) {
        fileService.removeByIds(Arrays.asList(ids));
        return Result.suc("批量删除成功");
    }

    // 分页查询
    @PostMapping("/listPage")
    @Logging(record = "分页查询文件列表" , type = "查询")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();

        // 提取查询参数
            String id = (String) param.get("id");
            String name = (String) param.get("name");
            String type = (String) param.get("type");
            String size = (String) param.get("size");
            String url = (String) param.get("url");
            String status = (String) param.get("status");
            String createTime = (String) param.get("createTime");

        // 分页配置
        Page<File> page = new Page<>();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<File> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                if (StringUtils.isNotBlank(id) && !"null".equals(id)) {
                    lambdaQueryWrapper.eq(File::getId, id);
                }
                if (StringUtils.isNotBlank(name) && !"null".equals(name)) {
                    lambdaQueryWrapper.like(File::getName, name);
                }
                if (StringUtils.isNotBlank(type) && !"null".equals(type)) {
                    lambdaQueryWrapper.like(File::getType, type);
                }
                if (StringUtils.isNotBlank(url) && !"null".equals(url)) {
                    lambdaQueryWrapper.like(File::getUrl, url);
                }
                if (StringUtils.isNotBlank(status) && !"null".equals(status)) {
                    lambdaQueryWrapper.eq(File::getStatus, status);
                }
                if (StringUtils.isNotBlank(createTime) && !"null".equals(createTime)) {
                    lambdaQueryWrapper.like(File::getCreateTime, createTime);
                }


        // 执行分页查询
        IPage result = fileService.PageList(page, lambdaQueryWrapper);
        return Result.suc(result.getTotal(), result.getRecords());
    }
}